<?php
namespace frontend\modules\Api\controllers;

use common\models\TallyMember;
use common\models\TallyProject;
use common\services\TallyMemberService;
use common\services\TallyProjectService;
use common\services\ToolService;
use common\services\UploadLocalServices;
use PhpOffice\PhpSpreadsheet\IOFactory;
use Yii;
use yii\filters\AccessControl;
use yii\helpers\ArrayHelper;
use yii\base\DynamicModel;

/**
 * Class MemberController
 *
 * @package frontend\modules\Api\controllers
 * @desc 成员管理
 */
class MemberController extends ApiController
{
    /**
     * @return array
     * 引入行为验证 过滤授权
     */
    public function behaviors()
    {
        $config = [
            'access' => [
                'class' => AccessControl::className(),
                'denyCallback' => function($rule, $action){
                    return self::failureResponse(100001, '请先登录!',[]);
                },
                'rules' => [
                    [
                        'allow' => true,
                        'roles' => ['@'],
                    ]
                ]
            ],
        ];
        return ArrayHelper::merge(parent::behaviors(), $config);
    }

    /**
     * @throws
     * 成员列表
     */
    public function actionLists()
    {
        $tallyId = Yii::$app->getRequest()->get('tally_id');
        if(!$tallyId){
            return self::failureResponse(500,'账本Id不能为空');
        }
        $this->checkRolePermission($this->_user['id'],$tallyId,'read');
        $condition = Yii::$app->request->get(); // type 等参数
        $list = TallyMemberService::getList($condition);
        return self::successResponse($list);
    }

    /**
     * @throws
     * 增加成员
     */
    public function actionAdd()
    {
        $form = DynamicModel::validateData([
            'name' => Yii::$app->getRequest()->post('name'),
            'tally_id' => Yii::$app->getRequest()->post('tally_id'),
            'uid'   => $this->_user['id'],
            'type'  => Yii::$app->getRequest()->post('type',1),
        ],[
            [['name','tally_id','type'], 'required'],
            ['name', 'filter', 'filter' => 'trim'],
            ['name', 'string','min'=> 1,'max'=> 10],
            ['type', 'integer'],
        ]);
        if ($form->hasErrors()) {
            return self::failureResponse(500,current($form->getFirstErrors()));
        }
        // 检查用户操作权限
        $this->checkRolePermission($this->_user['id'],$form->tally_id,'read');
        $result = TallyMemberService::create(ArrayHelper::toArray($form));
        if($result){
            return self::successResponse(['id'=>$result]);
        }else{
            return self::failureResponse(500,'新增失败.'.TallyMemberService::getError());
        }
    }

    /**
     * @throws
     * 编辑成员
     */
    public function actionEdit()
    {
        $form = DynamicModel::validateData([
            'id'    => Yii::$app->getRequest()->post('id'),
            'tally_id' => Yii::$app->getRequest()->post('tally_id'),
            'name' => Yii::$app->getRequest()->post('name',''),
        ],[
            [['name','id'], 'required'],
            ['name', 'filter', 'filter' => 'trim'],
            ['name', 'string','min'=> 1,'max'=> 10],
        ]);
        if ($form->hasErrors()) {
            return self::failureResponse(500,current($form->getFirstErrors()));
        }
        $result = TallyMemberService::update([
            'id'    => $form->id,
            'uid'   => $this->_user['id'],
        ],ArrayHelper::toArray($form));
        if($result){
            return self::successResponse();
        }else{
            return self::failureResponse(500,'更新失败.'.TallyMemberService::getError());
        }
    }

    /**
     * @throws
     * 删除成员
     */
    public function actionDel()
    {
        $id = Yii::$app->getRequest()->post('id');
        if(!$id){
            return self::failureResponse(500,'账户Id不能为空');
        }
        // 检查对账本的操作权限
        $tallyId = Yii::$app->getRequest()->post('tally_id');
        $this->checkRolePermission($this->_user['id'],$tallyId,'write');
        $result = TallyMemberService::delete([
            'id'    => $id,
            'tally_id' => $tallyId,
//            'uid'   => $this->_user['id']
        ]);
        if($result){
            return self::successResponse();
        }else{
            return self::failureResponse(500,'删除失败.'.TallyMemberService::getError());
        }
    }


    public function actionImportData(){
        $id = Yii::$app->getRequest()->post('tally_id');
        if(!$id){
            return self::failureResponse(500,'账本Id不能为空');
        }

        $fileRes = UploadLocalServices::uploadLocalFu();
        if($fileRes['code'] != 0){
            return  self::failureResponse(500,$fileRes['msg']);
        }
        $filePath = $fileRes['data']['path'];
        $spreadsheet = IOFactory::load($filePath);
        $data = $spreadsheet->getSheet(0)->toArray();
        $exitDatas = TallyMember::find()->where([
            'tally_id'=>$id
        ])->select('name')->asArray()->all();
        $exitDatas = array_column($exitDatas,'name');
        $in_data = [];
        foreach ($data as $key=>$value){
            if($key > 0 && !in_array($value[0],$exitDatas)){
                $in_data[] = [
                    'tally_id'=>$id,
                    'name'=>$value[0],
                    'uid'=>$this->_user['id']
                ];
                $exitDatas[] = $value[0];
            }
        }
        $res = Yii::$app->db->createCommand()->batchInsert('tally_member', ['tally_id', 'name','uid'], $in_data)->execute();
        if($res > 0){
            return self::successResponse();
        }
        return self::failureResponse(500,'导入失败');
    }


    public function actionExport(){
        $tally_id = Yii::$app->getRequest()->get('tally_id');
        if(!$tally_id){
            return self::failureResponse(500,'账户Id不能为空');
        }
        $condition = Yii::$app->getRequest()->get();
        $list = TallyMemberService::getList($condition);
        $retData = [] ;

        foreach ($list as $k=>$lv) {
            $retData[] = [
                $k+1,
                $lv['name'],
                $lv['created_time']."\t",
            ];
        }
        $filename = '员工导出-'.date('YmdHis').'-'.rand(1000,9999).'.csv';
        ToolService::downLoadCsv($filename,[
            '编号',
            '标题',
            '创建时间'
        ],$retData);
        $filepath = Yii::$app->request->hostInfo.'/index/down-export?file='.$filename;
        return self::successResponse(['filepath'=>$filepath]);
    }

}
